/*******************************************************************************
 * This file is part of blueprint4j www.blueprint4j.org.
 * 
 *     blueprint4j is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     blueprint4j is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with blueprint4j. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package blueprint4j.utils;

import java.util.*;

public class Cache {
	private long access_counter=0;
	private HashMap hashmap;
	private int size;
	
	public Cache(int size){
		this.size=size;
		hashmap=new HashMap(size);
	}
	
	public Object get(Object id){
		Entry e=(Entry)hashmap.get(id);
		if (e!=null){
			e.used=access_counter++;
			return e.value;
		}
		return null;
	}
	
	public void put(Object id,Object value){
		// Is size too big?
		if (hashmap.size()>=size){
			// Remove oldest
			Object old_id=getOldestId();
			if (old_id!=null){
				hashmap.remove(old_id);
			}
		}
		// Add new
		hashmap.put(id,new Entry(value));
	}
	
	private Object getOldestId(){
		Iterator i=hashmap.entrySet().iterator();
		long oldest=access_counter;
		Object id=null;
		while (i.hasNext()){
			Map.Entry me=(Map.Entry)i.next();
			Entry e=(Entry)me.getValue();
			if (e.used<oldest){
				oldest=e.used;
				id=me.getKey();
			}
		}
		return id;
	}
	
	static class Entry{
		long used=0;
		Object value;
		
		Entry(Object value){
			this.value=value;
		}
	}
}

